const http = require("http");
const { createCanvas, loadImage } = require("canvas");
const qs = require("querystring");

const server = http.createServer();
const IMG_URL_REG = /^\/\w+_w(\d+)_h(\d+).(png|jpg)/;
const BRAND_SIZE = 48;
const MAX_INPUT_WIDTH = 750;
const MAX_INPUT_HEIGHT = 3000;

server.on("request", function (req, res) {
  // 3.1 收到请求时，打印请求的路径

  const imgOption = req.url.match(IMG_URL_REG);
  let paramString = req.url.split("?")[1];
  let params = {};
  // console.log(params);
  if (paramString) {
    params = qs.parse(paramString);
    console.log(params);
  }
  if (imgOption) {
    let [url, width, height, format] = imgOption;
    width = Math.min(width, MAX_INPUT_WIDTH);
    height = Math.min(height, MAX_INPUT_HEIGHT);
    const canvas = createCanvas(Number(width), Number(height));

    const ctx = canvas.getContext("2d");
    if (params.bg && params.bg.length === "0xffffffff".length) {
      let imgData = ctx.getImageData(0, 0, width, height);
      let r = parseInt(params.bg.substr(4, 2), 16);
      let g = parseInt(params.bg.substr(6, 2), 16);
      let b = parseInt(params.bg.substr(8, 2), 16);
      let a = parseInt(params.bg.substr(2, 2), 16);
      for (var i = 0; i < imgData.data.length; i += 4) {
        // 当该像素是透明的，则设置成白色
        // console.log(parseInt(params.bg.substr(2, 2), 16));
        if (imgData.data[i + 3] == 0) {
          imgData.data[i] = r;
          imgData.data[i + 1] = g;
          imgData.data[i + 2] = b;
          imgData.data[i + 3] = a;
        }
      }
      ctx.putImageData(imgData, 0, 0);
    }
    loadImage("./brand.png").then((image) => {
      let [_brand_size, minSize] = [BRAND_SIZE, Math.min(width, height)];
      if (_brand_size > minSize) {
        _brand_size = (minSize / 2) >> 0;
      }
      ctx.drawImage(
        image,
        0.5 * (Math.min(width, params.mw || Infinity) - _brand_size),
        0.5 * (Math.min(height, params.mh || Infinity) - _brand_size),
        _brand_size,
        _brand_size
      );
      // console.log(ctx.getImageData(0, 0, width, height));
      // const stream = canvas.createPNGStream();
      let stream;
      if (format === "jpg") {
        res.setHeader("Content-Type", "image/jpeg");
        stream = canvas.createJPEGStream();
      } else {
        res.setHeader("Content-Type", "image/png");
        stream = canvas.createPNGStream();
      }
      let respData = [];
      stream.on("data", (chunk) => {
        respData.push(chunk);
      });
      stream.on("end", () => {
        res.write(Buffer.concat(respData));
        res.end();
      });
    });
  } else {
    res.end("not found");
    // throw new Error("请求文件格式不正确");
  }
});
server.listen(3000, function () {
  console.log("服务器启动成功");
});
